package com.yylending.las.authority.login;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.content.Loader;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.*;
import butterknife.*;
import cn.jpush.android.api.JPushInterface;
import com.tbruyelle.rxpermissions.Permission;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.infrastructure.mvp.IEvent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yylending.las.Global;
import com.yylending.las.R;
import com.yylending.las.YJKD;
import com.yylending.las.authority.password.ForgetPwdActivity;
import com.yylending.las.authority.register.RegistActivity;
import com.yylending.las.base.BaseActivity;
import com.yylending.las.common.location.LocationPresenter;
import com.yylending.las.common.location.entity.Location;
import com.yylending.las.StatIDSet;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.common.utils.PermissionUtil;
import com.yylending.las.common.widgets.CommonDialog;
import com.yylending.las.webview.WebViewActivity;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by HenryZhang on 2016/10/25.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class LoginActivity extends BaseActivity implements LoginPresenter.View, LocationPresenter.View {
	private final static String TAG = "LoginActivity";

	public final static String CLEAR_GESTURE = "clear_gesture";
	private static final int REQUEST_CODE_GPS = 100;
	public final static int REQUEST_CODE_REGISTER = 1;
	private final static int LOADER_ID_LOGIN = 1;
	private final static int LOADER_ID_LOCATE = 2;

	@BindView(R.id.login_phone_input)
	EditText mPhoneNumber;
	@BindView(R.id.login_delete_phone_number)
	ImageView mDeletePhoneNum;
	@BindView(R.id.login_password_input)
	EditText mPasswordEt;
	@BindView(R.id.login_delete_pwd)
	ImageView mPwdDelete;
	@BindView(R.id.login_submit_btn)
	Button mSubmitBtn;
	@BindView(R.id.login_user_deal_chb)
	CheckBox mUserDealChb;

	private LoginPresenter mLoginPresenter;
	private LocationPresenter mLocationPresenter;
	/**
	 * Flag
	 */
	//private boolean mAgreeFlag;
	/**
	 * 登录成功之后清除手势密码
	 */
	private boolean mClearGesture;
	/**
	 * 定位信息
	 */
	private Location mLocation;
	private String mPhone;
	private String mPassword;
	/**
	 * 是否需要在定位成功之后自动登录
	 */
	private boolean mAutoLogin;

	public static void start(RxAppCompatActivity aty) {
		Intent intent = new Intent(aty, LoginActivity.class);
		aty.startActivityForResult(intent, REQUEST_CODE_REGISTER);
	}

	public static void start(Activity aty, boolean clearGesture) {
		Intent intent = new Intent(aty, LoginActivity.class);
		intent.putExtra(CLEAR_GESTURE, clearGesture);
		aty.startActivity(intent);
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_LOGIN:
				mLoginPresenter = (LoginPresenter) data;
				mLoginPresenter.attach(this);
				break;
			case LOADER_ID_LOCATE:
				mLocationPresenter = (LocationPresenter) data;
				mLocationPresenter.attach(this);
				PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.ACCESS_COARSE_LOCATION);
				break;
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_LOGIN:
				return new PresenterLoader<>(this, new LoginPresenter.Generator());
			case LOADER_ID_LOCATE:
				return new PresenterLoader<>(this, new LocationPresenter.Generator());
		}
		return null;
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
		Global.setThirdPartyPageOpenedFlag(false);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		ButterKnife.bind(this);
		setTopBarVisible(false);
		mClearGesture = getIntent().getBooleanExtra(CLEAR_GESTURE, false);
		initView();
		getSupportLoaderManager().initLoader(LOADER_ID_LOGIN, null, this);
		getSupportLoaderManager().initLoader(LOADER_ID_LOCATE, null, this);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		mClearGesture = intent.getBooleanExtra(CLEAR_GESTURE, false);
	}

	@Override
	protected void onDestroy() {
		getSupportLoaderManager().destroyLoader(LOADER_ID_LOGIN);
		getSupportLoaderManager().destroyLoader(LOADER_ID_LOCATE);
		super.onDestroy();
	}

	private void initView() {
		if (!TextUtils.isEmpty(Global.LOGIN_ACCOUNT_NAME)) {
			mPhoneNumber.setText(Global.LOGIN_ACCOUNT_NAME);
			mPhoneNumber.setSelection(mPhoneNumber.getText().length());
			mDeletePhoneNum.setVisibility(View.VISIBLE);
		}
	}

	@OnTextChanged(value = R.id.login_password_input, callback = OnTextChanged.Callback.TEXT_CHANGED)
	public void onPasswordChanged(CharSequence s, int start, int before, int count) {
		if (s.length() != 0) {
			mPwdDelete.setVisibility(View.VISIBLE);
		} else {
			mPwdDelete.setVisibility(View.GONE);
		}
	}

	/**
	 * 输入手机号时监听
	 */
	@OnTextChanged(value = R.id.login_phone_input, callback = OnTextChanged.Callback.TEXT_CHANGED)
	public void onPhoneNumberChanged(CharSequence s, int start, int before, int count) {
		if (s.toString().trim().length() != 0) {
			mDeletePhoneNum.setVisibility(View.VISIBLE);
		} else {
			mDeletePhoneNum.setVisibility(View.GONE);
		}
	}

	/**
	 * 密码可见CheckBox监听
	 */
	@OnCheckedChanged(R.id.login_password_visiable_unvisiable)
	public void onPasswordChecked(CompoundButton btn, boolean checked) {
		if(checked){
			mPasswordEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
		}else{
			mPasswordEt.setTransformationMethod(PasswordTransformationMethod.getInstance());
		}
		mPasswordEt.setSelection(mPasswordEt.getText().length());//设置光标到最末尾
	}

	/**
	 * 处理用户协议是否勾选
	 */
	private void processClickCheckBoxDeal() {
		Boolean isCheck = mUserDealChb.isChecked();
		if (isCheck) {
			mSubmitBtn.setEnabled(true);
		} else {
			mSubmitBtn.setEnabled(false);
		}
	}

	/**
	 * 删除手机号码输入
	 */
	private void processDeletePhoneNum() {
		mPhoneNumber.getText().clear();
	}

	private boolean checkPhoneNumber() {
		boolean rs = false;
		if (TextUtils.isEmpty(mPhoneNumber.getText())) {
			showToast(getString(R.string.please_input_toast, getString(R.string.mobile_phone)));
			return false;
		}
		int length = mPhoneNumber.getText().length();
		if (length > 0) {
			if (mPhoneNumber.getText().toString().trim().length() < 11) {
				showToast(R.string.input_correct_phone);
			} else {
				rs = true;
			}
		}
		return rs;
	}

	private boolean checkPassword() {
		if(TextUtils.isEmpty(mPasswordEt.getText().toString().trim())){
			showToast(getString(R.string.please_input_toast, getString(R.string.password)));
			return false;
		}
		return true;
	}

	@OnClick({R.id.login_back_ic, R.id.register_user_agreement, R.id.login_user_deal_chb, R.id.login_delete_phone_number,
			R.id.login_submit_btn, R.id.login_register, R.id.login_forget_password, R.id.login_user_deal, R.id.login_delete_pwd})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.login_back_ic:
				finish();
				break;
			case R.id.register_user_agreement:
				mUserDealChb.setChecked(!mUserDealChb.isChecked());
				if (mUserDealChb.isChecked()) {
					mSubmitBtn.setEnabled(true);
				} else {
					mSubmitBtn.setEnabled(false);
				}
				break;
			//用户协议
			case R.id.login_user_deal_chb:
				processClickCheckBoxDeal();
				break;
			//删除输入手机号码
			case R.id.login_delete_phone_number:
				processDeletePhoneNum();
				break;
			//确定登录
			case R.id.login_submit_btn:
				YJKD.hideInputWindow(this);
				if (checkPhoneNumber() && checkPassword()) {
					showLoading(true);
					mAutoLogin = false;
					login();
				}
				break;
			case R.id.login_register:
				RegistActivity.start(this, REQUEST_CODE_REGISTER);
				break;
			case R.id.login_forget_password:
				ForgetPwdActivity.start(this, mPhoneNumber.getText().toString().trim());
				break;
			case R.id.login_user_deal:
				if (!TextUtils.isEmpty(Global.LOGIN_REGISTER_PROTOCOL_URL)) {
					CLog.i(TAG, "加载页面=" + Global.LOGIN_REGISTER_PROTOCOL_URL);
					WebViewActivity.start(this, Global.BASE_URL + Global.LOGIN_REGISTER_PROTOCOL_URL, getString(R.string.user_agreement_link), -1);
				}
				break;
			case R.id.login_delete_pwd:     //删除密码
				mPasswordEt.getText().clear();
				break;
			default:
				break;
		}
	}

	private void login(){
		mPhone = mPhoneNumber.getText().toString().trim();
		mPassword = mPasswordEt.getText().toString().trim();
		if(null == mLocation){
			mLoginPresenter.login(mPhone, mPassword, null, null);
		}else{
			mLoginPresenter.login(mPhone, mPassword, String.valueOf(mLocation.longitude), String.valueOf(mLocation.latitude));
		}
	}

	@Override
	public void loginSuccess() {
		CLog.i(TAG, "dismissLoading loginSuccess");
		if(!TextUtils.isEmpty(Global.LOGIN_USER_ID)){
			JPushInterface.setAlias(getApplicationContext(), 1, Global.LOGIN_USER_ID);
		}
		dismissLoading();
		setResult(RESULT_OK);
		if (mClearGesture) {//忘记手势密码时，登录成功后清除手势密码
			YJKD.clearGesture(false);
			YJKD.getInstance().setFingerprintOpen(false);
		}
		finish();
	}

	@Override
	public void loginFail(String msg) {
		CLog.i(TAG, "dismissLoading loginFail");
		dismissLoading();
		if (TextUtils.isEmpty(msg)) {
			showToast(R.string.phone_or_pwd_error);
		} else {
			showToast(msg);
		}
	}

	@Override
	public void loginRetCode(String retCode) {
		StatService.onEventWithSingleAttribute(this, StatIDSet.EVENT_ID_LOGIN,retCode);
	}

	@Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1)
	public void onMessageEvent(IEvent.LoginSuccessEvent event) {
		switch (event.id) {
			case IEvent.CODE_LOGIN_SUCCESS:
				finish();
				break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
				case REQUEST_CODE_REGISTER:
					CLog.i(TAG, "LoginActivity onActivityResult register");
					finish();
					break;
			}
		}
	}

	@Override
	public void onLocateSuccess(Location location) {
		mLocation = location;
		if(mAutoLogin) login();
	}

	@Override
	public void onLocateFail(boolean noPermission) {
		if(mAutoLogin){
			CLog.i(TAG, "dismissLoading onLocateFail");
			showToast(R.string.locate_need_retry);
			dismissLoading();
			mAutoLogin = false;
		}
	}

	@Override
	public void showDialog() {

	}

	@Override
	public void dismissDialog() {

	}

	private PermissionsGrantedHelper.PermissionsGrantedListener mGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
		@Override
		public void permissionsEachGrantedResult(Permission permission) {
			switch (permission.name) {
				case Manifest.permission.ACCESS_COARSE_LOCATION:
					if (permission.granted) {
						mLocationPresenter.startLocation(false);
					} else {
						if(mAutoLogin) {
							CLog.i(TAG, "dismissLoading permissionsEachGrantedResult");
							dismissLoading();
						}
					}
					break;
				default:
					break;
			}

		}

		@Override
		public void PermissionsAllGrantedResult(boolean granted, int requestCode) {

		}
	};
}
